<?php


namespace app\index\controller;


use app\index\model\Article as ArticleModel;
use think\facade\Db;
use think\facade\View;

class Article extends IndexController {
    protected $idList = [];

    protected function isIdInSession($article_id) {
        session_start();
        if (isset($_SESSION['articleIdList'])) {
            $this->idList = json_decode($_SESSION['articleIdList']);
            if (in_array($article_id, $this->idList)) {
                return true;
            } else {
                array_push($this->idList, $article_id);
                $_SESSION['articleIdList'] = json_encode($this->idList);
                return false;
            }
        } else {
            array_push($this->idList, $article_id);
            $_SESSION['articleIdList'] = json_encode($this->idList);
            return false;
        }
    }

    protected function incClicks($article_id) {
        if ($this->isIdInSession($article_id)) {
            return true;
        }
        $res = Db::table('jy_article')->
        where('id', $article_id)->
        inc('clicks')->
        update();
        if (!$res) {
            return show(config('status.error'), '更新点击量失败');
        }
        return true;
    }

    public function index() {
        $article = (new ArticleModel())->getArticleById($this->articleId);
        $this->incClicks($this->articleId);
        return View::fetch('',
            [
                'category' => $this->category,
                'category_name' => $this->categoryName,
                'bar' => $this->header,
                'banner' => $this->banner,
                'data' => $article,
                'info' => $this->info,
            ]);
    }
}